package org.itboys.mobile.controller.mobile.account;

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.dto.ResultPageDOHelper;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mdl.entity.mongo.account.SundayAccount;
import org.itboys.mdl.util.MobileSignUtils;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.service.mongo.mobile.account.SundayAccountService;
import org.itboys.mobile.util.AccountIdHoldUtils;
import org.itboys.mobile.util.ResponseMessage;
import org.itboys.param.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created on 2017/11/29.
 * @author 朱坤涛
 */
@Controller
@RequestMapping("/sunday/mobile/account")
@Api(value = "account",description = "账户")
public class SundayMobileAccountController extends BaseController{

    @Autowired
    private SundayAccountService accountService;

    /**
     * 新增账户
     * @param accountId
     * @param type
     * @param account
     * @param name
     * @param mobile
     * @param code
     * @param bank
     * @param request
     * @param response
     */
    @ApiOperation(value = "新增账户")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public void save(
            @ApiParam(required = true, name = "accountId", value = "账户Id,新增时传入0") @RequestParam(value = "accountId", required = false) Long accountId,
            @ApiParam(required = true, name = "type", value = "账户类型(1-银行卡 2-支付宝 3-微信)")@RequestParam(value = "type", required = true) Integer type,
            @ApiParam(required = true, name = "account", value = "账户号") @RequestParam(value = "account", required = true) String account,
            @ApiParam(required = true, name = "name", value = "账户名") @RequestParam(value = "name", required = true) String name,
            @ApiParam(required = true, name = "mobile", value = "填写银行卡预留手机号")@RequestParam(value = "mobile",required = true)String mobile,
            @ApiParam(required = true, name = "code", value = "验证码") @RequestParam(value = "code", required = true) String code,
            @ApiParam(required = false, name = "bank", value = "开户银行") @RequestParam(value = "bank", required = false) String bank,
            @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign,
            HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("accountId",accountId);
            param.put("type",type);
            param.put("account",account);
            param.put("name",name);
            param.put("mobile",mobile);
            param.put("code",code);
            param.put("bank",bank);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            accountService.saveAccount(accountId,memberId,name,bank,account,type,mobile,code);
            ResponseMessage.success();
        } catch (Exception e) {
            String msg =CommonConstants.ERROMSG;
            Integer code1=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code1=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/account/save----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code1,msg);
        }
    }

    /**
     * 获取账户列表
     * @param request
     * @param response
     */
    @ApiOperation(value = "获取账户列表")
    @RequestMapping(value = "/list",method = RequestMethod.POST)
    public void list(HttpServletRequest request,
                     HttpServletResponse response,
                     @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                     @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign){
        try {
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
           List<SundayAccount> result=accountService.selectAccount(memberId);
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code = CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                msg = e.getMessage();
                //token已过期
            } else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")) {
                code = CommonConstants.TOKEN_CODE;
                msg = CommonConstants.TOKENMSG;
            } else {
                logger.error("/sunday/mobile/account/list----e=" + e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code, msg);
        }
    }

    /**
     * 设置默认账户
     * @param request
     * @param response
     * @param accountId
     */
    @ApiOperation(value = "设置默认账户")
    @RequestMapping(value = "/setDefault",method = RequestMethod.POST)
    public void serDefault(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "accountId",required = true)Long accountId,
            @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign){
        try {
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("accountId",accountId);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            accountService.setDefaultAccount(accountId,memberId);
            ResponseMessage.success();
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code = CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                msg = e.getMessage();
                //token已过期
            } else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")) {
                code = CommonConstants.TOKEN_CODE;
                msg = CommonConstants.TOKENMSG;
            } else {
                logger.error("/sunday/mobile/account/setDefault----e=" + e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code, msg);
        }
    }

    /**
     * 获取默认账户
     * @param request
     * @param response
     */
    @ApiOperation(value = "获取默认账户")
    @RequestMapping(value = "/getDefault",method = RequestMethod.POST)
    public void getDefault(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign){
        try {
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            SundayAccount account = accountService.getDefaultAccount(memberId);
            ResponseMessage.success(account);
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code = CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                msg = e.getMessage();
                //token已过期
            } else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")) {
                code = CommonConstants.TOKEN_CODE;
                msg = CommonConstants.TOKENMSG;
            } else {
                logger.error("/sunday/mobile/account/getDefault----e=" + e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code, msg);
        }
    }

    /**
     * 删除账户
     * @param request
     * @param response
     * @param accountId
     */
    @ApiOperation(value = "删除账户")
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public void delete(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "accountId",required = true)Long accountId,
            @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign){
        try {
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("accountId",accountId);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }
            accountService.deleteAccount(accountId);
            ResponseMessage.success();
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code = CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                msg = e.getMessage();
                //token已过期
            } else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")) {
                code = CommonConstants.TOKEN_CODE;
                msg = CommonConstants.TOKENMSG;
            } else {
                logger.error("/sunday/mobile/account/delete----e=" + e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code, msg);
        }
    }
}
